﻿using Castle.Aop.AspectsHub.Attributes;
using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Castle.Aop.AspectsHub
{
    public class CastleInterceptor : AsyncInterceptorBase
    {

        private readonly IServiceProvider _serviceProvider;
        public CastleInterceptor(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        private IAspectContext _aopContext;
        private List<BaseAspectAttribute> _aops;
        private async Task Befor()
        {
            foreach (var aAop in _aops)
            {
                await aAop.Befor(_aopContext);
            }
        }
        private async Task After()
        {
            foreach (var aAop in _aops)
            {
                await aAop.After(_aopContext);
            }
        }
        private void Init(IInvocation invocation)
        {
            // 创建 CastleAspectContext 对象，用于存储当前方法调用的上下文信息
            _aopContext = new CastleAspectContext(invocation, _serviceProvider);

            // 获取目标方法上的所有 BaseAspectAttribute 属性
            // 并与目标对象 (invocation.InvocationTarget) 上的属性合并（也就是方法所属的这个类上面的属性）  
            // 获取当前目标方法和它所在的对象（类）上的所有 BaseAspectAttribute 属性，并将它们合并在一起，以便后续可以统一处理这些切面逻辑
            _aops = invocation.MethodInvocationTarget.GetCustomAttributes(typeof(BaseAspectAttribute), true)
                .Concat(invocation.InvocationTarget.GetType().GetCustomAttributes(typeof(BaseAspectAttribute), true))
                .Select(x => (BaseAspectAttribute)x)
                .ToList();
        }


        protected override async Task InterceptAsync(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func<IInvocation, IInvocationProceedInfo, Task> proceed)
        {
            try
            {
                Init(invocation);
                await Befor();
                Console.WriteLine($"{invocation.Method.Name}:Starting Void Method");
                await proceed(invocation, proceedInfo).ConfigureAwait(false);
                Console.WriteLine($"{invocation.Method.Name}:Completed Void  Method");
                await After();
            }
            catch (Exception e)
            {
                Console.WriteLine($"{invocation.Method.Name}:Throw Exception :{e.Message}");
                throw;
            }
        }

        protected override async Task<TResult> InterceptAsync<TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func<IInvocation, IInvocationProceedInfo, Task<TResult>> proceed)
        {
            try
            {
                Init(invocation);
                await Befor();
                Console.WriteLine($"{invocation.Method.Name}:Starting Result Method");
                TResult result = await proceed(invocation, proceedInfo).ConfigureAwait(false);
                Console.WriteLine($"{invocation.Method.Name}:Completed Result Method");
                await After();
                return result;
            }
            catch (Exception e)
            {
                Console.WriteLine($"{invocation.Method.Name}: Throw Exception Result:{e.Message}");
                throw;
            }
        }
    }
}
